<template>
  <div class="pay-ment">
    <el-dialog
        title="Total"
        :visible.sync="paymentVisible"
        width="808px"
        :modal="false"
        :close-on-click-modal="false"
        :before-close="handlePayClose">
      <div class="content">
        <div class="money">£ {{paymentData.total}}</div>
        <div class="pay-way">
          <el-radio-group v-model="payWay">
            <div class="bg">
              <el-radio label="1" border>
                <div class="flex">
                  <div>Membership card</div>
                  <div style="position: absolute;right: 26px">£ {{ balance }}</div>
                </div>
              </el-radio>
            </div>
          </el-radio-group>
        </div>
        <div class="coupon">
          <span class="title">Voucher</span>
          <el-select v-model="coupon" placeholder="Vouchers" @change="handleCoupon">
            <el-option
                v-for="item in couponList"
                :key="item.id"
                :value="item.id">
              <span style="float: left">{{item.name}}</span>
              <span style="float: right">{{item.expireTime}}</span>
            </el-option>
          </el-select>
        </div>
        <div style="display: flex;justify-content: space-between;margin-bottom: 40px;">
          <div></div>
          <div><span style="margin-right: 10px">Total：£ {{Number(total).toFixed(2)}}</span> Discount：£ {{Number(discountMoney).toFixed(2)}}</div>
        </div>
        <div class="pay-btn">
          <el-button @click="handlePayment" :loading="paymentStatus">Payment</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapState} from "vuex";
import calculation from "../utils/calculation";
import {getAllCoupons, handleClientPay} from "../api/shopMall";

export default {
  name: "payment",
  props: {
    paymentVisible: {
      type: Boolean,
      defaulted: false
    },
    paymentData: {
      type: Object,
      defaulted: {}
    }
  },
  computed: {
    ...mapState({
      couponData: state => state.coupons.couponList,
      balance:state => state.coupons.balance,
      comData:state => state.comData.comData,
      subCategory:state => state.comData.subCategory
    })
  },
  data() {
    return {
      payWay: '1',
      coupon: '',
      selectCoupon: '',
      couponList: [],
      total:0,
      discountMoney:0,
      paymentStatus:false
    }
  },
  mounted() {
    this.total = this.paymentData.total
    console.log(this.subCategory.subCategory)
    getAllCoupons(this.comData).then(res => {
      this.$store.dispatch('coupons/getCouponList', res.data).then(() => {
        this.couponList = this.myFilter(this.couponData,this.paymentData.goodsList,this.subCategory.subCategory)
        this.couponList.unshift({id:'',name:'NA'})
      })
    })
  },
  methods: {
    handlePayClose() {
      this.$emit('handlePayClose')
    },
    myFilter(arr1, arr2,arr3) {
      let newData = []
      arr1.forEach((ele) =>{
        let list = ele.productId.split(',')
        list.forEach(item => {
          let id = item.split('-')[1]
          arr2.forEach(res => {
            if (id == res.categoryId) newData.push(ele)
            arr3.forEach(v => {
              if (id == v.id && res.subCategory ==  v.id) newData.push(ele)
            })
          })
        })
      });
      newData = this.deWeightThree(newData)
      return newData
    },
    deWeightThree(arr) {
      let map = new Map();
      for (let item of arr) {
        if (!map.has(item.id)) {
          map.set(item.id, item);
        }
      }
      return [...map.values()];
    },
    handlePayment(){
      if(this.paymentData.goodsList.length === 0){
        this.$message.error('请选择商品');
        return false
      }
      // if(calculation.accSub(this.balance,1)>Number(this.total)){
        this.paymentStatus = true
        let data = this.comData
        data.goodsList = this.paymentData.goodsList
        data.payType = 2
        data.coupons = this.selectCoupon?[{id:this.selectCoupon}]:[]
        data.payAmount = calculation.accMul(this.total,100)
        data.totalAmount = calculation.accMul(this.paymentData.total,100)
        data.disAmount = calculation.accMul(this.discountMoney,100)
        handleClientPay(JSON.stringify(data)).then(res => {
          this.paymentStatus = false
          if(res.data.code !== 0){
            this.$emit('handlePayClose')
            this.$store.dispatch('success/changeSuccess',res.data.msg)
            this.$store.dispatch('cart/clearCart')
          }else {
            this.$emit('handlePayClose')
            this.$store.dispatch('error/changeError',res.data.msg)
            this.$store.dispatch('cart/clearCart')
          }
        })
      // }else {
      //   this.$message.error('No sufficient funds');
      // }
    },

    handleCoupon(v){
      this.selectCoupon = v
      this.couponList.forEach(item => {
        if(item.id === v){
          this.coupon = item.name
        }
      })
      if(v){
        let productId = []
        let couponList = this.couponList.filter(item => {
          if(item.id === v) {
            let list = item.productId.split(',')
            list.forEach(v => {
              let id = v.split('-')[1]
              productId.push(id)
            })
          }
          return item.id === v
        })
        let num = calculation.accSub(100,couponList[0].discount)
        // console.log(num)
        let discount = calculation.accDiv(num,100)
        // console.log(discount)
        let goodList = this.paymentData.goodsList.filter(item => productId.filter(v => v == item.categoryId).length)

        if(!goodList.length){
          goodList = this.paymentData.goodsList.filter(item => productId.filter(v => v == item.subCategory).length)
        }
        console.log(goodList)

        // console.log(goodList)
        let retailPrice = Math.max.apply(Math,goodList.map(ele => {return Number(ele.total)}))

        let newRetailPrice = 0
        for(let i=0;i<goodList.length;i++){
          if(goodList[i].total==retailPrice){
            goodList[i].couponuse=couponList[0].id;
            goodList[i].couponname=couponList[0].name;
            newRetailPrice = calculation.accDiv(retailPrice,goodList[i].num)
            break;
          }
        }

        let discountMoney = calculation.accMul(newRetailPrice,discount)
        // console.log(retailPrice)
        // console.log(discount)
        // console.log(discountMoney)
        this.discountMoney = discountMoney
        this.total = calculation.accSub(this.paymentData.total , discountMoney)
      }else {
        this.discountMoney = 0
        this.total = this.paymentData.total
      }
    }
  }
}
</script>

<style scoped lang="scss">
.pay-ment {
  ::v-deep .el-dialog {
    background: rgba(0, 0, 0, 0.9);
    border-radius: 42px;

    .el-dialog__header {
      padding-bottom: 0;
    }

    .el-dialog__body {
      color: #ffffff;
      padding: 0 32px;

      .bg {
        padding-bottom: 19px;
        border-bottom: 1px dashed #979797;
      }

      .money {
        font-size: 35px;
        padding: 11px 0;
      }

      .el-radio-group {
        width: 100%;

        .el-radio {
          width: 100%;
          height: 54px;
          line-height: 54px;
          background: linear-gradient(90deg, #FFE96B 0%, #FFD55C 12%, #FFBC49 32%, #FFAA3C 53%, #FF9F34 75%, #FF9C32 100%);
          box-shadow: 0 16px 19px -15px rgba(144, 2, 252, 0.41);
          border-radius: 11px;
          background-size: 100% 100%;
          border: none;
          color: #141413;
          font-size: 22px;
          padding: 0 18px 22px;

          .el-radio__input, .el-radio__label {
            float: left;
            color: #ffffff;
          }

          .el-radio__input.is-checked .el-radio__inner {
            border-color: #ffffff;
            background: #FC3C02;
          }

          .el-radio__input {
            margin-top: 16px;
          }

          .flex {
            display: flex;
            justify-content: space-between;
          }
        }
      }

      .coupon {
        position: relative;
        height: 58px;
        margin-bottom: 10px;

        .title {
          position: absolute;
          left: 10px;
          line-height: 58px;
          font-size: 18px;
        }

        .el-select {
          width: 100%;
          height: 100%;
          border-bottom: 1px dashed #979797;

          .el-input__inner {
            background: rgba(0, 0, 0, .1);
            border: none;
            text-align: right;
            height: 58px !important;
            line-height: 58px;
          }

          .el-select__tags {
            justify-content: flex-end;
          }
        }
      }

      .pay-btn {
        text-align: center;
        padding-bottom: 18px;

        button {
          width: 252px;
          height: 67px;
          background: linear-gradient(90deg, #FFE96B 0%, #FFD55C 12%, #FFBC49 32%, #FFAA3C 53%, #FF9F34 75%, #FF9C32 100%);
          border-radius: 33px;
          border: none;
          color: #ffffff;
          font-size: 24px;
        }
      }
    }

  }
}
</style>
